/**
 * Author: w景洋.
 * Time: 2016/7/14 0014
 */

angular.module('usercenter.service.recharge', [
        'ngResource',
    ])

    .service('WxRecharge', ['$resource', function ($resource) {
        //"http://120.55.194.39:81/usercenter/recharge/wxjsapipay"

        var recharge = $resource(uc_rechargeurl + "wxjsapipay");

        var openid_res = $resource(uc_payconfig.wxpay_url + "openid");//根据code去接口找openid

        this.wxrechargePay = function (rechargedata, success_func, error_func) {

            rechargedata.fund = rechargedata.payment;

            //获取OpenID
            if (!$storage.wxpay_openid) {
                var reg = new RegExp("(^|&)" + "code" + "=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                var authcode = "xxxxxxxxxxxxxxxxxx";
                if (r) {
                    authcode = unescape(r[2]);
                }
                openid_res.get({wxspid: uc_payconfig.wxpay_spid, code: authcode}).$promise.then(function (data) {
                    if (data.openid) {
                        uc_payconfig.wxpay_openid = data.openid;
                        rechargedata.openid = data.openid;
                        recharge.save(rechargedata, success_func, error_func);
                    } else {
                        var jump_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
                            + uc_payconfig.wxpay_appid + "&redirect_uri=" + uc_payconfig.wxpay_backurl
                            + "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
                        window.location.href = jump_url;
                    }
                }, function (error) {
                    //alert(error);
                });
            } else {
                rechargedata.openid = $storage.wxpay_openid;
                //支付调起
                return recharge.save(rechargedata, success_func, error_func);
            }
        }

    }])

    .service('AliRecharge', ['$http', '$q', function ($http, $q) {

        var apiUrl = uc_rechargeurl + "aliwappay"

        this.alirechargePay = function (rechargedata) {
            rechargedata.fund = rechargedata.payment;
            rechargedata.sellerid = uc_payconfig.alipay_appid;
            rechargedata.show_url = "http://www.nonggui8.com/mobile/";
            rechargedata.return_url = "http://www.nonggui8.com/mobile/mywealth";
            var deferred = $q.defer();
            $http({
                method: "POST",
                url: apiUrl,
                data: rechargedata
            }).success(function (data, status, headers, config) {
                deferred.resolve(data);
            }).error(function (data, status, headers, config) {
                deferred.reject(data);
            });
            return deferred.promise;
        };
    }])